package org.jeecg.modules.planProduction.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.basicParts.entity.BasicParts;
import org.jeecg.modules.basicParts.service.IBasicPartsService;
import org.jeecg.modules.basicProducts.entity.BasicPartsDetail;
import org.jeecg.modules.basicProducts.entity.BasicProducts;
import org.jeecg.modules.basicProducts.service.IBasicPartsDetailService;
import org.jeecg.modules.basicProducts.service.IBasicProductsService;
import org.jeecg.modules.planProduction.entity.PlanProduction;
import org.jeecg.modules.planProduction.entity.PlanProductsDetail;
import org.jeecg.modules.planProduction.entity.PlanPartsDetail;
import org.jeecg.modules.planProduction.mapper.PlanProductsDetailMapper;
import org.jeecg.modules.planProduction.mapper.PlanPartsDetailMapper;
import org.jeecg.modules.planProduction.mapper.PlanProductionMapper;
import org.jeecg.modules.planProduction.service.IPlanPartsDetailService;
import org.jeecg.modules.planProduction.service.IPlanProductionService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * @Description: 生产计划
 * @Author: jeecg-boot
 * @Date:   2025-02-10
 * @Version: V1.0
 */
@Service
@Slf4j
public class PlanProductionServiceImpl extends ServiceImpl<PlanProductionMapper, PlanProduction> implements IPlanProductionService {

	@Autowired
	private PlanProductionMapper planProductionMapper;
	@Autowired
	private PlanProductsDetailMapper planProductsDetailMapper;
	@Autowired
	private PlanPartsDetailMapper planPartsDetailMapper;

	@Autowired
	private IBasicProductsService basicProductsService;
	@Autowired
	private IBasicPartsService basicPartsService;
	@Autowired
	private IBasicPartsDetailService basicPartsDetailService;
	@Autowired
	private IPlanPartsDetailService planPartsDetailService;
	
	@Override
	@Transactional
	public void saveMain(PlanProduction planProduction, List<PlanProductsDetail> planProductsDetailList,List<PlanPartsDetail> planPartsDetailList) {
		planProductionMapper.insert(planProduction);
		if(planProductsDetailList!=null && planProductsDetailList.size()>0) {
			for(PlanProductsDetail entity:planProductsDetailList) {
				//外键设置
				entity.setPlanId(planProduction.getId());
				planProductsDetailMapper.insert(entity);
			}
		}
		if(planPartsDetailList!=null && planPartsDetailList.size()>0) {
			for(PlanPartsDetail entity:planPartsDetailList) {
				//外键设置
				entity.setPlanId(planProduction.getId());
				planPartsDetailMapper.insert(entity);
			}
		}
	}

	@Override
	@Transactional
	public void updateMain(PlanProduction planProduction,List<PlanProductsDetail> planProductsDetailList,List<PlanPartsDetail> planPartsDetailList) {
		planProductionMapper.updateById(planProduction);
		
		//1.先删除子表数据
		planProductsDetailMapper.deleteByMainId(planProduction.getId());
		planPartsDetailMapper.deleteByMainId(planProduction.getId());
		
		//2.子表数据重新插入
		if(planProductsDetailList!=null && planProductsDetailList.size()>0) {
			for(PlanProductsDetail entity:planProductsDetailList) {
				//外键设置
				entity.setPlanId(planProduction.getId());
				planProductsDetailMapper.insert(entity);
			}
		}
		if(planPartsDetailList!=null && planPartsDetailList.size()>0) {
			for(PlanPartsDetail entity:planPartsDetailList) {
				//外键设置
				entity.setPlanId(planProduction.getId());
				planPartsDetailMapper.insert(entity);
			}
		}
	}

	@Override
	@Transactional
	public void delMain(String id) {
		planProductsDetailMapper.deleteByMainId(id);
		planPartsDetailMapper.deleteByMainId(id);
		planProductionMapper.deleteById(id);
	}

	@Override
	@Transactional
	public void delBatchMain(Collection<? extends Serializable> idList) {
		for(Serializable id:idList) {
			planProductsDetailMapper.deleteByMainId(id.toString());
			planPartsDetailMapper.deleteByMainId(id.toString());
			planProductionMapper.deleteById(id);
		}
	}

	@Transactional
	@Override
	public Result<?> release(String id) {
		PlanProduction byId = baseMapper.selectById(id);
		if (byId == null) {
			return Result.error("未找到对应数据");
		}
		if (1 != byId.getStatus()) {
			return Result.error("生产计划状态错误");
		}
		List<PlanPartsDetail> list = planPartsDetailMapper.selectByMainId(id);
		if(list.isEmpty()){
			return Result.error("无部品明细无法发布");
		}
		// 更新生产计划状态和发布时间
		byId.setStatus(2);
		byId.setReleaseTime(new Date());
		for (PlanPartsDetail planPartsDetail : list) {
			Integer number = planPartsDetail.getNumber();
			String volume = planPartsDetail.getVolume();
			planPartsDetail.setTotalVolume(String.valueOf(new BigDecimal(volume).multiply(new BigDecimal(number))));
		}
		updateById(byId);
		planPartsDetailService.updateBatchById(list);
		return Result.OK("发布成功！");
	}

	/**
	 * 根据生产计划制品明细, 创建所需部品明细
	 * @param id 生产计划id
	 */
	@Override
	public void createPartsDetail(String id) {
		List<PlanProductsDetail> planProductsDetails = planProductsDetailMapper.selectByMainId(id);
		if (planProductsDetails.isEmpty()) {
			log.info("没有找到生产计划ID为 {} 的制品明细", id);
			return;
		}

		// 获取所有需要的产品SKU
		Set<String> productsSkus = planProductsDetails.stream()
				.map(PlanProductsDetail::getProductsSku)
				.collect(Collectors.toSet());

		// 批量获取基础产品信息
		Map<String, BasicProducts> basicProductsMap = basicProductsService.getByProductsSkus(productsSkus);
		if (basicProductsMap.isEmpty()) {
			log.warn("没有找到任何基础产品信息");
			return;
		}

		// 初始化部品数量映射
		Map<String, Integer> partsQuantityMap = new HashMap<>();

		for (PlanProductsDetail planProductsDetail : planProductsDetails) {
			String productsSku = planProductsDetail.getProductsSku();
			int quantity = planProductsDetail.getNumber();

			BasicProducts basicProduct = basicProductsMap.get(productsSku);
			if (basicProduct == null) {
				log.warn("基础产品 SKU 为 {} 的产品不存在", productsSku);
				continue;
			}

			List<BasicPartsDetail> basicPartsDetails = basicPartsDetailService.selectByMainId(basicProduct.getId());
			for (BasicPartsDetail basicPartsDetail : basicPartsDetails) {
				String partsSku = basicPartsDetail.getPartsSku();
				int partsNumber = basicPartsDetail.getNumber() * quantity;
				partsQuantityMap.merge(partsSku, partsNumber, Integer::sum);
			}
		}

		// 获取所有需要的部品SKU
		Set<String> partsSkus = partsQuantityMap.keySet();

		// 批量获取基础部件信息
		Map<String, BasicParts> basicPartsMap = basicPartsService.getByPartsSkus(partsSkus);
		if (basicPartsMap.isEmpty()) {
			log.warn("没有找到任何基础部件信息");
			return;
		}

		List<PlanPartsDetail> planPartsDetailsToInsert = new ArrayList<>();
		for (Map.Entry<String, Integer> entry : partsQuantityMap.entrySet()) {
			String partsSku = entry.getKey();


			BasicParts basicPart = basicPartsMap.get(partsSku);

			if (basicPart == null) {
				log.warn("基本部件 SKU 为 {} 的部件不存在", partsSku);
				continue;
			}

			int totalNumber;
			if(StringUtils.isEmpty(basicPart.getPacketNum())){
				totalNumber = entry.getValue();
			} else {
				totalNumber = (entry.getValue() + basicPart.getPacketNum() - 1) / basicPart.getPacketNum();
			}

			PlanPartsDetail planPartsDetail = new PlanPartsDetail();
			planPartsDetail.setPlanId(id);
			planPartsDetail.setPartsSku(partsSku);
			planPartsDetail.setPartsBack(basicPart.getPartsBack());
			planPartsDetail.setNumber(totalNumber);
			planPartsDetail.setEuType(basicPart.getEuType());
			planPartsDetail.setVolume(basicPart.getVolume());
			planPartsDetail.setWarehouseId(basicPart.getWarehouseId());

			planPartsDetailsToInsert.add(planPartsDetail);
		}

		if (!planPartsDetailsToInsert.isEmpty()) {
			planPartsDetailMapper.deleteByMainId(id);
			planPartsDetailService.saveBatch(planPartsDetailsToInsert);
			log.info("成功创建 {} 条部品明细", planPartsDetailsToInsert.size());
		} else {
			log.info("没有生成新的部品明细");
		}
	}

}
